package com.lzp.java.concurrent.flowcontrol.cyclicbarrier;

import java.util.concurrent.*;

/**
 * @author lzp
 * @Description: 多个线程同时到达某个地点，同时出发。
 * @date 2021/3/7
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        // 初始化循环栅栏
        CyclicBarrier barrier = new CyclicBarrier(5, () -> {
            System.out.println("所有线程到齐，开始出发。。。");
        });
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            pool.submit(new Task(i, barrier));
        }
    }

    static class Task implements Runnable {
        int id;
        CyclicBarrier barrier;

        public Task(int id, CyclicBarrier barrier) {
            this.id = id;
            this.barrier = barrier;
        }

        @Override
        public void run() {

            try {
                System.out.println("线程" + id + "到达出发点。。。");
                TimeUnit.MILLISECONDS.sleep((long) (Math.random() * 1000));
                System.out.println("线程" + id + "已到达，等待出发。。。");
                barrier.await();
                System.out.println("线程" + id + "开始出发。。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }
}
